/**
 * 简洁的标签页管理器
 */

class TabsManager {
    constructor() {
        this.tabs = [];
        this.activeTabId = null;
        this.tabContainer = null;
        this.init();
    }
    
    init() {
        // 立即检查是否已有标签页容器
        const existingContainer = document.querySelector('.app-tabs-container');
        if (existingContainer) {
            // 如果已存在，直接使用
            this.tabContainer = existingContainer;
            this.chromeTabsEl = existingContainer.querySelector('.app-tabs-list');
            this.setupEvents();
            this.loadSavedTabs();
        } else {
            // 如果不存在，创建新的
            setTimeout(() => {
                this.createTabContainer();
                this.loadSavedTabs();
            }, 50);
        }
    }
    
    createTabContainer() {
        // 检查是否已存在标签页容器
        const existing = document.querySelector('.app-tabs-container');
        if (existing) {
            this.tabContainer = existing;
            this.chromeTabsEl = existing.querySelector('.app-tabs-list');
            this.setupEvents();
            return;
        }
        
        // 创建标签页容器HTML
        const tabsHTML = `
            <div class="app-tabs-container">
                <div class="app-tabs-wrapper">
                    <div class="app-tabs-list" id="tabsList">
                        <!-- 标签页将在这里动态生成 -->
                    </div>
                    <div class="app-tabs-actions">
                        <button class="app-tab-add-btn" id="newTabBtn" title="新建标签页">
                            <i class="bi bi-plus"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // 插入到主容器的最顶部
        const mainContainer = document.querySelector('.main-container');
        if (mainContainer) {
            mainContainer.insertAdjacentHTML('afterbegin', tabsHTML);
            this.tabContainer = mainContainer.querySelector('.app-tabs-container');
            this.chromeTabsEl = this.tabContainer.querySelector('.app-tabs-list');
            this.setupEvents();
        }
    }
    
    setupEvents() {
        // 新建标签页
        document.getElementById('newTabBtn')?.addEventListener('click', () => {
            this.openTab('定制编辑器', '/customize', true);
        });
    }
    
    openTab(title, url, isActive = false) {
        const tabId = this.generateTabId();
        const tab = {
            id: tabId,
            title: title,
            url: url,
            isActive: isActive,
            canClose: true
        };
        
        // 如果是当前页面，标记为活跃
        if (window.location.pathname === url || isActive) {
            this.setActiveTab(tabId);
        }
        
        this.tabs.push(tab);
        this.renderTabs();
        this.saveTabs();
        
        return tabId;
    }
    
    closeTab(tabId) {
        const tabIndex = this.tabs.findIndex(t => t.id === tabId);
        if (tabIndex === -1) return;
        
        const tab = this.tabs[tabIndex];
        if (!tab.canClose) return;
        
        // 如果关闭的是当前活跃标签，切换到其他标签
        if (this.activeTabId === tabId) {
            const nextTab = this.tabs[tabIndex + 1] || this.tabs[tabIndex - 1];
            if (nextTab) {
                this.switchTab(nextTab.id);
            }
        }
        
        this.tabs.splice(tabIndex, 1);
        this.renderTabs();
        this.saveTabs();
    }
    
    switchTab(tabId) {
        const tab = this.tabs.find(t => t.id === tabId);
        if (!tab) return;
        
        // 保存当前页面状态
        if (window.editorCache) {
            window.editorCache.saveState();
        }
        
        // 立即更新活跃状态，避免闪烁
        this.setActiveTab(tabId);
        
        // 跳转到目标页面
        if (window.location.pathname !== tab.url) {
            window.location.href = tab.url;
        }
    }
    
    setActiveTab(tabId) {
        this.tabs.forEach(tab => {
            tab.isActive = tab.id === tabId;
        });
        this.activeTabId = tabId;
        this.renderTabs();
        this.saveTabs();
    }
    
    renderTabs() {
        const tabsContainer = this.chromeTabsEl;
        if (!tabsContainer) return;
        
        // 清除现有标签页
        const existingTabs = tabsContainer.querySelectorAll('.chrome-tab');
        existingTabs.forEach(tab => tab.remove());
        
        // 渲染新标签页
        this.tabs.forEach((tab, index) => {
            const tabEl = document.createElement('div');
            tabEl.className = `chrome-tab ${tab.isActive ? 'chrome-tab-current' : ''}`;
            tabEl.setAttribute('data-tab-id', tab.id);
            
            // 简化的标签页结构
            tabEl.innerHTML = `
                <div class="chrome-tab-content">
                    <div class="chrome-tab-favicon">${this.getTabIcon(tab.title)}</div>
                    <div class="chrome-tab-title">${tab.title}</div>
                    ${tab.canClose ? `<button class="chrome-tab-close" onclick="event.stopPropagation(); tabsManager.closeTab('${tab.id}')" title="关闭">
                        <i class="bi bi-x"></i>
                    </button>` : ''}
                </div>
            `;
            
            // 添加点击事件
            tabEl.addEventListener('click', (e) => {
                if (!e.target.closest('.chrome-tab-close')) {
                    this.switchTab(tab.id);
                }
            });
            
            tabsContainer.appendChild(tabEl);
        });
    }
    
    getTabIcon(title) {
        if (title.includes('定制') || title.includes('编辑')) return '🎨';
        if (title.includes('底板') || title.includes('模板')) return '🖼️';
        if (title.includes('导出') || title.includes('管理')) return '📁';
        if (title.includes('工作台') || title.includes('首页')) return '🏠';
        return '📄';
    }
    
    generateTabId() {
        return 'tab_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    saveTabs() {
        try {
            localStorage.setItem('app_tabs', JSON.stringify(this.tabs));
            localStorage.setItem('app_active_tab', this.activeTabId);
        } catch (e) {
            console.error('保存标签页失败:', e);
        }
    }
    
    loadSavedTabs() {
        try {
            const savedTabs = localStorage.getItem('app_tabs');
            const savedActiveTab = localStorage.getItem('app_active_tab');
            
            if (savedTabs) {
                this.tabs = JSON.parse(savedTabs);
                this.activeTabId = savedActiveTab;
            }
            
            // 确保当前页面有对应的标签
            this.ensureCurrentPageTab();
            this.renderTabs();
        } catch (e) {
            console.error('加载标签页失败:', e);
            this.ensureCurrentPageTab();
        }
    }
    
    ensureCurrentPageTab() {
        const currentPath = window.location.pathname;
        const currentTab = this.tabs.find(tab => tab.url === currentPath);
        
        if (!currentTab) {
            let title = '当前页面';
            if (currentPath.includes('customize')) {
                title = '图片定制';
            } else if (currentPath.includes('templates')) {
                title = '底板管理';
            } else if (currentPath.includes('exports')) {
                title = '导出管理';
            } else if (currentPath === '/') {
                title = '工作台';
            }
            
            this.openTab(title, currentPath, true);
        } else {
            this.setActiveTab(currentTab.id);
        }
    }
}

// 全局标签页管理器初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否已初始化
    if (window.GLOBAL_TABS_STATE && window.GLOBAL_TABS_STATE.initialized) {
        // 如果已初始化，只更新当前页面状态
        if (window.GLOBAL_TABS_STATE.manager) {
            window.GLOBAL_TABS_STATE.manager.ensureCurrentPageTab();
            window.tabsManager = window.GLOBAL_TABS_STATE.manager;
        }
    } else {
        // 首次初始化
        window.tabsManager = new TabsManager();
        window.GLOBAL_TABS_STATE.initialized = true;
        window.GLOBAL_TABS_STATE.manager = window.tabsManager;
    }
});
